package com.bric.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;

import com.bric.util.StaticStr;

public class FtpUpload {
	private static final Logger log=Logger.getLogger(FtpUpload.class);
//	private static String ftpRoot=null;
//	private static String ftpBackUp=null;
//	private static String fileRoot=null;
//	static{
//		ftpRoot=PropertiesUtil.getValue("ftpRoot");
//		fileRoot=PropertiesUtil.getValue("fileRoot");
//		ftpBackUp=PropertiesUtil.getValue("ftpBackUp");
//	}
	/** 
     * 连接FTP 
     *  
     * @param ip 
     * @param port 端口
     * @param userName 用户名
     * @param password 登陆密码
     * @param file 文件/文件流
     * @param remotePathName  目标地址
     * @param remoteName  目标文件名
     */  
    public static void upload(String ip, int port, String userName,  
            String password, File file, String remotePathName, String remoteName) {  
        FTPClient ftpClient = new FTPClient();  
        try {  
            ftpClient.connect(ip, port);  
            ftpClient.login(userName, password);  
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
            ftpClient.enterLocalPassiveMode();  
            log.info("ftp连接成功...");
            // 上传文件  
//            upload(ftpClient, file,StaticStr.fileRoot+remotePathName, remoteName,true);  
            upload(ftpClient, file,StaticStr.finalFileRoot+remotePathName, remoteName,true);  
            log.info("上传ftp成功...");
        } catch (Exception e) {  
            log.info("上传文件出现异常"+e.getMessage());
        } finally {  
            if (ftpClient != null && ftpClient.isConnected()) {  
                try {  
                    ftpClient.disconnect();  
                } catch (IOException e) {  
                    log.info("ftp fails to disconnect : "  
                            + e.getMessage());  
                }  
            }  
        }  
    }  
  
    /** 
     * 上传文件 
     *  
     * @param ftpClient 
     * @param file 
     * @param remotePathName 
     * @param remoteName 
     */  
    private static void upload(FTPClient ftpClient, File file,  
            String remotePathName, String remoteName,boolean isOverWrite) throws Exception {  
        try {  
            // 1. 切目录  
        	log.info("第一步，切目录");
            changeDirectory(ftpClient, remotePathName);
            if(isOverWrite){
            	log.info("重复文件，备份文件");
            // 2.判断当前目录下的文件与上传文件是否重名
            dupRemove(ftpClient,remotePathName,file,remoteName);
            }
            // 3. 传文件  
            log.info("开始正式上传");
            uploadFile(ftpClient, file, remotePathName, remoteName);  
            // 4. 切回根目录  
            log.info("回到根目录");
            backToRootDirectory(ftpClient);  
        } catch (IOException e) {  
        	log.info("上传出现异常"+e.getMessage());
        }  
    }  
  
    private static void dupRemove(FTPClient ftpClient, String remotePathName, File file, String remoteName) {
    	try {
			FTPFile[] ftps=ftpClient.listFiles();
			//System.out.println(ftps[0].getName()+"  "+ftps.length+"  "+remoteName);
			for(int i=0;i<ftps.length;i++){
				if(ftps[i].getName().equals(remoteName)){
					//changeDirectory(ftpClient, "backup/"+remotePathName);
//					ftpClient.rename(remoteName, "back/"+remoteName+"_"+sdf.format(new Date())+".bk");
					String url=file.getAbsolutePath();
//					int index=url.lastIndexOf("\\");
					int index=url.lastIndexOf(File.separator);
					String localPath=url.substring(0, index);
					File direct=new File(localPath+File.separator+"temp");
					direct.mkdirs();
					File localFile = new File(localPath+File.separator+"temp"+File.separator+ftps[i].getName()); 
					OutputStream is = new FileOutputStream(localFile); 
					ftpClient.retrieveFile(ftps[i].getName(), is); 
					is.close();
//					 backToRootDirectory(ftpClient);
//					remotePathName=remotePathName.substring(StaticStr.fileRoot.length(),remotePathName.length());
					remotePathName=remotePathName.substring(StaticStr.finalFileRoot.length(),remotePathName.length());
//					upload(ftpClient, localFile, StaticStr.ftpBackUp+remotePathName, remoteName, false);
					upload(ftpClient, localFile, StaticStr.finalFtpBackUp+remotePathName, remoteName, false);
					ftpClient.dele(remoteName);
				}
			}
		} catch (IOException e) {
			log.info(""+e.getMessage());
		} catch (Exception e) {
			log.info(""+e.getMessage());
		}
		
	}

	/** 
     * 切换目录 
     *  
     * @param ftpClient 
     * @param path 
     * @throws IOException 
     */  
    private static void changeDirectory(FTPClient ftpClient, String path)  
            throws IOException {  
        int nextSeperator = path.indexOf("/", 1);  
        String currentPath = null;  
        if (nextSeperator < 0) {  
            nextSeperator = path.length();  
            currentPath = path.substring(0, nextSeperator);  
            changeDirectory0(ftpClient, currentPath);  
            return;  
        } else {  
            currentPath = path.substring(0, nextSeperator);  
            changeDirectory0(ftpClient, currentPath);  
            changeDirectory(ftpClient, path.substring(nextSeperator+1));  
        }  
    }  
  
    /** 
     * 如果切换的目录不存在 就创建一个新的目录 
     *  
     * @param ftpClient 
     * @param path 
     * @throws IOException 
     */  
    private static void changeDirectory0(FTPClient ftpClient, String path)  
            throws IOException {  
        if (!ftpClient.changeWorkingDirectory(path)) {  
            ftpClient.makeDirectory(path);  
        }  
        ftpClient.changeWorkingDirectory(path);  
    }  
  
    /** 
     * 回到根目录根 
     *  
     * @param ftpClient 
     * @throws IOException 
     */  
    private static void backToRootDirectory(FTPClient ftpClient)  
            throws IOException {  
        ftpClient.changeWorkingDirectory("/");  
    }  
  
    /** 
     * 真正的上传文件方法 
     *  
     * @param ftpClient 
     * @param file 
     * @param remotePathName 
     * @param remoteName 
     */  
    private static void uploadFile(FTPClient ftpClient, File file,  
            String remotePathName, String remoteName) throws Exception {  
    	////此处存疑？？？
//    	ftpClient.changeWorkingDirectory(StaticStr.fileRoot+remotePathName);  
    	ftpClient.changeWorkingDirectory(StaticStr.finalFtpRoot+remotePathName);  
    	String localPathName = file.getAbsolutePath();  
        try {
        	FTPFile[] files = ftpClient.listFiles();  
        	if (files.length == 1) {  
        		if (!ftpClient.deleteFile(remoteName)) {  
        			throw new Exception("fail to delete remote file ["  
        					+ remotePathName + "] before uploading");  
        		}  
        	}  
		} catch (Exception e) {
			e.printStackTrace();
		}
        File f = new File(localPathName);  
        InputStream is = new FileInputStream(f);  
        if (!ftpClient.storeFile(remoteName, is)) {  
            is.close();  
        }  
        is.close();  
    }  
    
    /*public static void main(String[] args) {
    	File file=new File("D:/fagaiwei.zip");
//    	FtpUpload.upload(StaticStr.ftpIp, Integer.parseInt(StaticStr.ftpPort), StaticStr.ftpUser, StaticStr.ftpPasswd, file, "", "data.zip");
    	FtpUpload.upload("192.168.20.2", 21, "ftptest", "123456789", file, "", "data.zip");
//		upload("192.168.20.2", 21, "ftptest", "123456789", file, "aaa/123", "key.txt");
	}*/
}
